package com.innovation.chengzhangriji.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.innovation.chengzhangriji.BabyAndParent;
import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.Parent;
import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.database.DatabaseManager;
import com.innovation.chengzhangriji.http.Auth;
import com.innovation.chengzhangriji.http.BabyAllResponse;
import com.innovation.chengzhangriji.http.Client;
import com.innovation.chengzhangriji.http.ResponseHandler;
import com.innovation.chengzhangriji.preferences.LoginInfo;
import com.innovation.chengzhangriji.ui.widget.BabyAllAdapter;
import com.orhanobut.logger.Logger;

public class BabyAllFragment extends BaseFragment implements BabyAllAdapter.OnClickItemListener {

    private RecyclerView mRecyclerView;

    private BabyAllAdapter mBabyAllAdapter;

    private boolean isAdmin;

    private int length;

    private BabyAllResponse[] info;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1000 && resultCode == Activity.RESULT_OK) {
            mBabyAllAdapter.clear();
            mBabyAllAdapter.notifyDataSetChanged();
            requestBabyAll();
        }
        if (requestCode == 1000 && resultCode == -1000) {
            // getActivity().finish();
            // 删除日记成功
            Intent intent = new Intent(getContext(), HomeActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_baby_all, container, false);
        mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler);
        RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getActivity(), 3);
        mRecyclerView.setLayoutManager(layoutManager);
        mBabyAllAdapter = new BabyAllAdapter(getActivity());
        mBabyAllAdapter.setOnClickItemListener(this);
        mRecyclerView.setAdapter(mBabyAllAdapter);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        requestBabyAll();
    }

    @Override
    public void onClickItem(BabyAllResponse babyAllResponse) {
        if (!isAdmin) {
            return;
        }
        Intent intent;
        switch (babyAllResponse.getAuth().getRole()) {
            case 0:
                intent = new Intent(getActivity(), AdminActivity.class);
                break;
            case 1:
                intent = new Intent(getActivity(), AdminActivity.class);
                break;
            case 2:
                intent = new Intent(getActivity(), SuperAdminActivity.class);
                break;
            default:
                intent = new Intent(getActivity(), SuperAdminActivity.class);
                break;
        }
        Gson gson = new Gson();
        String permission = gson.toJson(babyAllResponse);
        intent.putExtra("permission", permission);
        intent.putExtra("length", length);
        Gson gson2 = new Gson();
        String sInfo = gson2.toJson(info);
        intent.putExtra("info", sInfo);
        startActivityForResult(intent, 1000);
    }

    private void requestBabyAll() {
        LoginInfo loginInfo = Config.getLoginInfo(getActivity());
        if (loginInfo == null) {
            return;
        }
        String phone = loginInfo.getPhone();
        String token = loginInfo.getToken().getAccessToken();
        final String userId = loginInfo.getUserID();
        final int babyId = loginInfo.getBabyID();
        BabyAndParent babyAndParent = DatabaseManager.getInstance(getActivity()).queryBabyAndParent(userId, babyId);
        isAdmin = babyAndParent.getRole() == 2;

        // 判断网络
        if (!isNetworkConnect(getActivity())) {
            Parent[] parents = DatabaseManager.getInstance(getActivity()).queryParent(babyId);
            if (parents == null || parents.length == 0) {
                return;
            }
            BabyAllResponse[] responses = new BabyAllResponse[parents.length];
            length = responses.length;
            info = responses;
            for (int i = 0; i < parents.length; i++) {
                responses[i] = new BabyAllResponse();
                responses[i].setType(parents[i].getType());
                responses[i].setUserId(parents[i].getParentId());
                responses[i].setUser(parents[i].getUser());
                responses[i].setName(parents[i].getName());
                responses[i].setPhone(parents[i].getPhone());
                responses[i].setServerTS(parents[i].getServerTS());
                responses[i].setMessage(parents[i].getMessage());
                responses[i].setPath(parents[i].getPath());
                responses[i].setNickName(parents[i].getNickName());
                Auth auth = new Auth();
                auth.setRole(parents[i].getRole());
                auth.setPermission(parents[i].getPermission());
                auth.setRange(parents[i].getRange());
                responses[i].setAuth(auth);
                mBabyAllAdapter.add(responses[i]);
            }
            mBabyAllAdapter.notifyDataSetChanged();
            return;
        }

        Client.requestBabyAll(getActivity(), phone, token, babyId, new ResponseHandler() {

            @Override
            public void onInnovationSuccess(JsonElement value) {
                super.onInnovationSuccess(value);
                JsonObject object = value.getAsJsonObject();
                JsonArray jsonArray = object.getAsJsonArray("Messages");
                BabyAllResponse[] responses = get(jsonArray.toString(), BabyAllResponse[].class);
                if (responses == null) {
                    return;
                }
                length = responses.length;
                info = responses;
                Parent[] parents = new Parent[responses.length];
                for (int i = 0; i < responses.length; i++) {
                    mBabyAllAdapter.add(responses[i]);
                    parents[i] = new Parent();
                    parents[i].setBabyId(babyId);
                    parents[i].setType(responses[i].getType());
                    parents[i].setParentId(responses[i].getUserId());
                    parents[i].setUser(responses[i].getUser());
                    parents[i].setName(responses[i].getName());
                    parents[i].setPhone(responses[i].getPhone());
                    parents[i].setServerTS(responses[i].getServerTS());
                    parents[i].setMessage(responses[i].getMessage());
                    parents[i].setPath(responses[i].getPath());
                    parents[i].setNickName(responses[i].getNickName());
                    parents[i].setRole(responses[i].getAuth().getRole());
                    parents[i].setPermission(responses[i].getAuth().getPermission());
                    parents[i].setRange(responses[i].getAuth().getRange());
                }
                DatabaseManager.getInstance(getActivity()).insertOrReplaceInTxParent(parents);
                mBabyAllAdapter.notifyDataSetChanged();
            }

        }, networkUnavailableSampleImpl());
    }

    private static boolean isNetworkConnect(Context context) {
        ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (conMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED
                || conMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED
                || conMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTING
                || conMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTING) {
            return true;
        } else if (conMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.DISCONNECTED
                || conMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.DISCONNECTED) {
            return false;
        }
        return false;
    }
}
